﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using PmSoft.Exceptions;
using ManagementApi.Models;
using PmSoft.Utilities;
using PmSoft;
using PmSoft.ApplicationContext;
using ManagementApi.Models.System.Setting;

namespace ManagementApi.Mvc.Authorization
{
    /// <summary>
    /// 针对App用户进行验证
    /// </summary>
    public class AppAuthorizationAttribute : Attribute, IResourceFilter
    {
        /// <summary>
        /// 请求之前
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            var applicationContext = context.HttpContext.RequestServices.GetService<ManagementApplicationContext>();
            if (applicationContext == null)
                throw new ArgumentNullException(nameof(applicationContext));

            var userInfo = applicationContext.GetStateResolver<IAppUserInfo>("CurrentAppUser");
            if (userInfo == null)
            {
                context.Result = new JsonResult(ApiResult.Failure("请先登录").Encrypt());/* new JsonResult(ApiResult.Failure("请先登录"))*/;
                return;
            }
            else
            {
                if (userInfo.ExpireTime < DateTime.Now)
                {
                    context.Result = new JsonResult(ApiResult.Failure("身份认证过期,请重新登录"));
                    return;
                }
            }
        }

        /// <summary>
        /// 请求之后
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            string key = context.HttpContext.Request.Path;  //请求的路径
            //KeyValues[key] = context.Result;
        }
    }
}